//
//  WLMyCardsVController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/11.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLMyCardsVController.h"
#import "WLCardCollectionCell.h"
#import "UIScrollView+EmptyDataSet.h"

static NSString *cardCell = @"cardCell";

@interface WLMyCardsVController ()<UICollectionViewDelegate,UICollectionViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>//UICollectionViewDelegateFlowLayout

@property (nonatomic, strong) NSMutableArray    *arrCards;
@property (strong, nonatomic) UICollectionView  *collectionView;
@property (nonatomic, assign) NSInteger     cardNum;
@property (nonatomic, strong) NSMutableArray    *arrOpens;

@end

@implementation WLMyCardsVController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"我的卡券";
    
    _cardNum = 1;
    _arrOpens = [[NSMutableArray alloc] init];
    _arrCards = [[NSMutableArray alloc] init];
    UICollectionViewFlowLayout *flowLatyout = [[UICollectionViewFlowLayout alloc] init];
    CGFloat width = WIDTH_SCREEN_WL-WLScaleX(32);
    CGFloat height = WLScaleX(200);
    flowLatyout.itemSize = CGSizeMake(width, height);
    flowLatyout.sectionInset = UIEdgeInsetsMake(WLScaleX(20), WLScaleX(16), WLScaleX(10), WLScaleX(16));
    flowLatyout.minimumInteritemSpacing = WLScaleX(10);
    flowLatyout.minimumLineSpacing = WLScaleX(10);
    flowLatyout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowLatyout];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.emptyDataSetSource = self;
    _collectionView.emptyDataSetSource = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    [_collectionView registerClass:[WLCardCollectionCell class] forCellWithReuseIdentifier:cardCell];
    
    WLWkSelf
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    _collectionView.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.cardNum = 1;
        weakSelf.collectionView.mj_footer = nil;
        [weakSelf reqUserCards];
    }];
    
    [self reqUserCards];
}

- (void)addCardFooterRefresh
{
    WLWkSelf
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reqUserCards];
    }];
}

- (void)reqUserCards
{
    WLWkSelf
    NSDictionary *conditions = @{};
    NSDictionary *pages = @{@"page":@(_cardNum),@"num":@10};
    NSDictionary *paramsp = @{@"conditions":conditions,@"page":pages};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"card/app/user/list" withParamsDic:paramsp success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.collectionView.mj_header endRefreshing];
        NSInteger cardCount = [successDict[@"count"] integerValue];
//        if (strongSelf.cardNum==1&&flowCount>10)
//        {
//            [strongSelf addCardFooterRefresh];
//        }
        if (strongSelf.cardNum==1)
        {
            [strongSelf.arrCards removeAllObjects];
            if (cardCount>10)
            {
                [strongSelf addCardFooterRefresh];
            }
        }
        NSArray *arrList = successDict[@"object"];
        if (arrList.count>0)
        {
//            [strongSelf.collectionView.mj_footer endRefreshing];
            [strongSelf.arrCards addObjectsFromArray:arrList];
            if (strongSelf.arrCards.count >= cardCount) {
                [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.collectionView.mj_footer endRefreshing];
            }
            [strongSelf.collectionView reloadData];
        }
        else
        {
            [strongSelf.collectionView.mj_footer endRefreshingWithNoMoreData];
        }
        strongSelf.cardNum += 1;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf.collectionView.mj_header endRefreshing];
        [weakSelf.collectionView.mj_footer endRefreshing];
    } inView:(_cardNum==1&&_collectionView.mj_header.isRefreshing==NO)?self.view:nil];
}

#pragma mark collectionView代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _arrCards.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WLCardCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cardCell forIndexPath:indexPath];
    
    NSDictionary *dictCard = self.arrCards[indexPath.row];
    NSString *strImg = dictCard[@"imgPath"];
    if (strImg.length>6&&[strImg isKindOfClass:[NSNull class]]==NO) {
        [cell.ivBack sd_setImageWithURL:[NSURL URLWithString:strImg] placeholderImage:nil];
    }
    NSString *strCode = [NSString stringWithFormat:@"%@",dictCard[@"code"]];
    cell.labCardNum.text = [WLCommonTool strAddBlankFormatter:strCode];
//    NSString *strPwd = [NSString stringWithFormat:@"%@",dictCard[@"password"]];
//    cell.labPwd.text = [WLCommonTool strAddBlankFormatter:strPwd];
//    NSString *strPrice = [NSString stringWithFormat:@"¥%@",dictCard[@"rmb"]];
//    NSMutableAttributedString *attrPrice = [[NSMutableAttributedString alloc] initWithString:strPrice];
//    [attrPrice addAttribute:NSFontAttributeName
//                       value:[WLCommonTool fontTypePingFangSCSemibold:48]
//                       range:NSMakeRange(1, strPrice.length-1)];
//    cell.labPrice.attributedText = attrPrice;
    
    cell.btnEye.tag = indexPath.row;
    [cell.btnEye addTarget:self action:@selector(eyeAction:) forControlEvents:UIControlEventTouchUpInside];
    BOOL isContain = NO;
    for (NSNumber *subNum in _arrOpens) {
        if ([subNum integerValue]==indexPath.row)
        {
            isContain = YES;
            break;
        }
    }
    if (isContain) {
        [cell.btnEye setImage:[UIImage imageNamed:@"eye_open"] forState:UIControlStateNormal];
        NSString *strPwd = [NSString stringWithFormat:@"%@",dictCard[@"password"]];
        cell.labPwd.text = [WLCommonTool strAddBlankFormatter:strPwd];
        cell.labPwd.font = [WLCommonTool fontTypePingFangSCRegular:12];
    }
    else
    {
        [cell.btnEye setImage:[UIImage imageNamed:@"eye_close"] forState:UIControlStateNormal];
        cell.labPwd.text = @"**** **** **** ****";
        cell.labPwd.font = [WLCommonTool fontTypePingFangSCRegular:14];
    }
    
    return cell;
}

- (void)eyeAction:(UIButton *)eyeBtn
{
    NSNumber *num = [NSNumber numberWithInteger:eyeBtn.tag];
    BOOL isContain = NO;
    for (NSNumber *subNum in _arrOpens) {
        if ([subNum integerValue]==eyeBtn.tag)
        {
            num = subNum;
            isContain = YES;
            break;
        }
    }
    if (isContain) {
        [_arrOpens removeObject:num];
    }
    else
    {
        NSNumber *num = [NSNumber numberWithInteger:eyeBtn.tag];
        [_arrOpens addObject:num];
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:eyeBtn.tag inSection:0];
    [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - DZNEmpty
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"no_data"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"还没有卡券哦~";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[WLCommonTool fontTypePingFangSCRegular:17],
                                 NSForegroundColorAttributeName:wlDarkGrayColor
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}
@end
